package com.caishi.lkx.distribution.api;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.caishi.lkx.common.context.UserContext;
import com.caishi.lkx.distribution.model.DistributionWithdrawalSummary;
import com.caishi.lkx.distribution.properties.WeixinModel;
import com.caishi.lkx.distribution.service.IDistributionWithdrawalSummaryService;
import com.caishi.lkx.distribution.service.IOrderService;
import com.caishi.lkx.order.model.OrderModel;
import com.caishi.lkx.user.model.DistributionUser;
import com.caishi.lkx.user.service.IDistributionUserService;
import com.caishi.lkx.utils.TransferToUser;
import com.caishi.lkx.utils.WXPayUtility;
import com.zzw.common.utils.UUIDUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Map;

@RestController
@RequestMapping("/distribute/order")
public class OrderController {
    private final IOrderService orderService;
    private final WeixinModel weixinModel;
    private final TransferToUser transferToUser;
    private final UserContext userContext;
    private final IDistributionUserService distributionUserService;
    private final IDistributionWithdrawalSummaryService distributionWithdrawalSummaryService;

    public OrderController(IOrderService orderService, WeixinModel weixinModel, TransferToUser transferToUser, UserContext userContext, IDistributionUserService IDistributionUserService, IDistributionWithdrawalSummaryService distributionWithdrawalSummaryService) {
        this.orderService = orderService;
        this.weixinModel = weixinModel;
        this.transferToUser = transferToUser;
        this.userContext = userContext;
        this.distributionUserService = IDistributionUserService;
        this.distributionWithdrawalSummaryService = distributionWithdrawalSummaryService;
    }

//    @GetMapping("/list")
//    public Page<OrderModel> orderList(Page<OrderModel> page, Map<String, Object> params){
//        return orderService.orderList(page,params);
//    }
    @PostMapping("/transfer")
    public TransferToUser.TransferToUserResponse transfer(@RequestBody Map<String, Object> requestBody) throws Exception {
        // 先获取openid与access_token
        Map<String, Object> result = TransferToUser.getOpenId(weixinModel.getFwAppid(), weixinModel.getFwAppSecret(), (String)requestBody.get("code"));
        Map<String, Object> userInfo = TransferToUser.getUserInfo((String) result.get("access_token"), (String) result.get("openid"));
        // 打印昵称
//        System.out.println(userInfo.get("nickname"));
        if(result.get("openid")==null){
            return null;
        }
        // 必须是分销员
        QueryWrapper<DistributionUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",userContext.currentUserId());
        DistributionUser one = distributionUserService.getOne(queryWrapper, true);
        if(one==null){
            throw new Exception("请先注册为分销员");
        }

        // 如果金额超出分销员能转出的余额，返回无效响应

        DistributionWithdrawalSummary amountData = distributionWithdrawalSummaryService.getById(userContext.currentUserId());
        if(amountData==null){
            throw new Exception("您还为分销产品");
        }
        if(amountData.getCanTransfer()<Long.parseLong(requestBody.get("amount").toString())){
            throw new Exception("金额超出可转出余额");
        }

        TransferToUser.TransferToUserRequest request = new TransferToUser.TransferToUserRequest();
        request.appid = weixinModel.getFwAppid();
        // 根据一定规则生成，随机生成
        Long l = UUIDUtil.generateUUID();
        request.outBillNo = l.toString();

        request.transferSceneId = weixinModel.getTransferSceneId();
        request.openid =(String) result.get("openid");
//        request.userName = client.encrypt("user_name");

        request.transferAmount = Long.valueOf(requestBody.get("amount").toString());
        request.transferRemark = "佣金报酬";
//        request.notifyUrl = "https://www.weixin.qq.com/wxpay/pay.php";//选填
//        request.userRecvPerception = "现金奖励";//暂不支持
        request.transferSceneReportInfos = new ArrayList<>();
        {
            TransferToUser.TransferSceneReportInfo item0 = new TransferToUser.TransferSceneReportInfo();
            item0.infoType = "岗位类型";
            item0.infoContent = "分销员";
            request.transferSceneReportInfos.add(item0);
            TransferToUser.TransferSceneReportInfo item1 = new TransferToUser.TransferSceneReportInfo();
            item1.infoType = "报酬说明";
            item1.infoContent = "佣金报酬";
            request.transferSceneReportInfos.add(item1);
        };
        try {
            // 前端确认收帐
            return  transferToUser.run(request);
        } catch (WXPayUtility.ApiException e) {

            e.printStackTrace();
            return null;
        }
    }
}
